const db = require("../db/mysql")
const uuid = require("../utils/config")
const returns=require("../utils/returns");



const examService = {
    /**
     * 默认题库试题详情根据题目Id查询题目选项
     * @param {*} tid 题目id
     */
    getQuestionOptions:async(tid)=>{
            const sql=`SELECT * from exam_options where OQID=?`
            const result =await db.query(sql,tid);

            if(result==null){
               return returns.error(result);
            }

             let data=[];
             result.forEach(d => {
                   data.push({
                    Contentd:d.OContent,
                    IsRight:d.OIsRight
                })
             });
             return returns.success(data);
    
        },

    /**
     * 查询默认题库试题的试题列表的题目详情
     * @param {*} tid 题目id
     */
    getQuestionDetails:async(tid)=>{
        const sql=`SELECT 
        eq.QID,eq.QContent,eq.QType,eq.QLv,eq.QUseCount,eq.QIsPublish,us.UName,eq.QLabel,eq.QIsBan,eq.QCreateTime,eq.QExplain
        from exam_questions eq INNER JOIN users us ON eq.QAuthor=us.UID 
        where eq.QID=?`
        const result =await db.query(sql,tid);
        if( result==null){
            return{
                code:-500,
                message:"数据可能出现异常,请联系管理员进行处理"
            }
         }
         //将时间转化为时间戳并重新保存 
        // console.log( Date.parse("Fri Dec 10 2021 09:27:00 GMT+0800"));
        
         result.map(d=>{
            d.QCreateTime=Date.parse(d.QCreateTime)
         })

         return{
            code:0,
            message:"ok",
            data:{
                data:result
            }
        }

    },
    /**
     * 获取当前页面满足勾选的复选框的默认题库试题的试题列表
     * @param {*} page 
     * @param {*} limit 
     * @param {*} key 
     * @param {*} IsPusblish 默认题库题目的已经发布与未发布
     * @param {*} IsBan 默认题库题目的禁用与恢复
     */
    queryAllQuestionChecks:async(page,limit,key,IsPusblish,IsBan)=>{
        /**
         * 2是IsBan不作为条件查询
         */
        if(IsPusblish==""){
            IsPusblish='0,1';
        }else{
            IsPusblish=`${IsPusblish}`;
        };
         
        /**
         * 2是IsPusblish为不作为条件查询
         */
        if(IsBan==""){
            IsBan='0,1';
        }else{
            IsBan=`${IsBan}`;
        };
   
        let pages=(page-1)*10;
        const sql=` SELECT 
         eq.QID,eq.QContent,eq.QType,eq.QLv,eq.QUseCount,eq.QIsPublish,us.UName,eq.QLabel,eq.QIsBan,eq.QCreateTime
         from exam_questions eq INNER JOIN users us ON eq.QAuthor=us.UID 
         where  eq.QContent like '%${key}%' and eq.QIsPublish in (${IsPusblish}) and  eq.QIsBan in (${IsBan}) order by eq.QCreateTime desc limit ${pages},${limit}`;
         const result=await db.query(sql);
         if( result==null){
            return{
                code:-500,
                message:"数据可能出现异常,请联系管理员进行处理"
            }
         }
         //将时间转化为时间戳并重新保存 
        // console.log( Date.parse("Fri Dec 10 2021 09:27:00 GMT+0800"));
        
         result.map(d=>{
            d.QCreateTime=Date.parse(d.QCreateTime)
         })
        


         const sql2=` SELECT 
        count(*)as count
         from exam_questions eq INNER JOIN users us ON eq.QAuthor=us.UID 
         where  eq.QContent like '%${key}%' and eq.QIsPublish in (${IsPusblish}) and  eq.QIsBan in (${IsBan})`;
         const result2=await db.query(sql2);
         console.log(sql2);
         return{
            code:0,
            message:"ok",
            data:{
                data:result,
                total:result2[0].count
            }
        }

      },
      /**
     *  默认题库题目的禁用与恢复 传值1/0
     * @param {*} id 
     * @param {*} IsBan 
     * @returns 
     */
      TopicIsBan:async(id,IsBan)=>{
        const sql="UPDATE exam_questions SET QIsBan=? WHERE QID=?";
        const result=await db.query(sql,IsBan,id);
        if(result==null || result.affectedRows==0){
            return{
                code:-500,
                message:"参数错误"
            }
        }

        if(result.affectedRows>0){
            return{
                code:0,
                message:"操作成功"
            }
        }
    },
    
    /**
     * 默认题库删除题目
     */
    delQUestion:async(id)=>{
        const sql=" DELETE from exam_questions WHERE QID=?";
        const result=await db.query(sql,id);
        if(result==null || result.affectedRows==0){
            return{
                code:-500,
                message:"参数错误"
            }
        }

        if(result.affectedRows>0){
            return{
                code:0,
                message:"操作成功"
            }
        }
    },
    /**
     * 默认题库发布题目
     * @param {*} qid 
     * @param {*} IsPublish 
     * @returns 
     */
    TopicIsPublish:async(qid,IsPublish)=>{
        const sql="UPDATE exam_questions SET QIsPublish=? WHERE QID=?";
        const result=await db.query(sql,IsPublish,qid);
        if(result==null || result.affectedRows==0){
            return{
                code:-500,
                message:"参数错误"
            }
        }

        if(result.affectedRows>0){
            return{
                code:0,
                message:"操作成功"
            }
        }
    },
    /**
     * 查询默认题库试题的试题列表  /非默认题库试题共用方法 根据传入题库的id进行区分
     * @param {*} page 
     * @param {*} limit 
     * @param {*} key 
     * @returns 
     */
    queryAllQuestion:async(page,limit,key,params)=>{
        let pages=(page-1)*limit;
        let sql='';
        if(params==-1){
         sql=` SELECT 
         eq.QID,eq.QContent,eq.QType,eq.QLv,eq.QUseCount,eq.QIsPublish,us.UName,eq.QLabel,eq.QIsBan,eq.QCreateTime
         from exam_questions eq INNER JOIN users us ON eq.QAuthor=us.UID 
         where  eq.QContent like '%${key}%' order by eq.QCreateTime desc limit ${pages},${limit}`;
        }else{
            sql=` SELECT 
            eq.QID,eq.QContent,eq.QType,eq.QLv,eq.QUseCount,eq.QIsPublish,us.UName,eq.QLabel,eq.QIsBan,eq.QCreateTime
            from exam_questions eq INNER JOIN users us ON eq.QAuthor=us.UID 
            where  eq.QContent like '%${key}%' 
            and eq.QID in ( SELECT  QBDQID from exam_questionbankdetails where QBDQBID ='${params}' )
            order by eq.QCreateTime desc limit ${pages},${limit}`;
         }
         const result=await db.query(sql);
         if( result==null){
            return{
                code:-500,
                message:"数据可能出现异常,请联系管理员进行处理"
            }
         }
        
         //将时间转化为时间戳并重新保存 
        // console.log( Date.parse("Fri Dec 10 2021 09:27:00 GMT+0800"));
        
         result.map(d=>{
            d.QCreateTime=Date.parse(d.QCreateTime)
         })
        
         let sql2='';
         if(params==-1){
          sql2=` SELECT 
         count(*)as count
         from exam_questions eq INNER JOIN users us ON eq.QAuthor=us.UID 
         where  eq.QContent like '%${key}%' `;
        }else{
            sql2=` SELECT 
            count(*)as count
            from exam_questions eq INNER JOIN users us ON eq.QAuthor=us.UID 
            where  eq.QContent like '%${key}%'
            and eq.QID in ( SELECT  QBDQID from exam_questionbankdetails where QBDQBID ='${params}' ) `;
        }
         const result2=await db.query(sql2);
         return{
            code:0,
            message:"ok",
            data:{
                data:result,
                total:result2[0].count
            }
        }

    },
    /**
     * 
     * @param {*} uid 题目id
     * @param {*} content 题目内容
     * @param {*} typeX 题目类型 1选择题 2简答题
     * @param {*} lv 难度
     * @param {*} label 题目标签
     * @param {*} options 题目答案选项
     * @param {*} analysis 解析
     * @returns 
     */
    addTopic:async(uid,content,typeX,lv,label, options,analysis)=>{
           const qid= uuid.UUID()
            const sql=`INSERT INTO exam_questions
             (QID,QContent,QExplain,QType,QLv,QUseCount,QLabel,QAuthor,QIsPublish,QIsBan,QState,QCreateTime) 
             VALUES(?,?,?,?,?,0,?,?,0,0,1,now())`;
            const result=await db.query(sql,qid,content,analysis,typeX,lv,label.join(","),uid);

             if(result==null){
                return{
                    code:-500,
                    message:"数据可能出现异常,请联系管理员进行处理"
                }
            };
            

            for (let i = 0; i < options.length; i++) {
                let oids= uuid.UUID()
                const sql2=" INSERT INTO  exam_options (OID,OQID,OContent,OIsRight) values(?,?,?,?)";
                const result2=await db.query(sql2,oids,qid,options[i].content,options[i].isRight)
                if(result2==null){
                    return{
                        code:-500,
                        message:"数据可能出现异常,请联系管理员进行处理"
                    }
                };
            }
            
            return{
                code:0,
                message:"ok"
            }
    },

    /**
     * 添加题库
     * @param {*} QBName 题库名称
     * @param {*} QBCount 题库数量
     * @param {*} QBParent 
     * @param {*} QBLabel 题库类型/标签
     * @param {*} QBLv 题库难度
     * @param {*} QBlsPublish 是否发布 默认未发布
     * @param {*} QBlsBan 是否禁用 默认启用
     * @param {*} QBExplain 题库描述
     * @param {*} QBDesc 备用列
     * @returns 
     */
    addQuestion:async(QBName,QBCount,QBParent,QBLabel, QBLv,QBlsPublish,QBlsBan,QBExplain,QBDesc)=>{
       let labels=QBLabel.join(",");
       console.log(labels);
        const sql="INSERT into exam_questionbank VALUES(?,?,?,?,?,now(),?,?,?,?,?)";
        const result = await db.query(sql,uuid.UUID(),QBName,QBCount,QBParent,labels,QBLv,QBlsPublish,QBlsBan,QBExplain,QBDesc)
        // obj.QBName,obj.QBCount,obj.QBParent,obj.QBLabel, obj.QBLv,obj.QBlsPublish, obj.QBlsBan,obj.QBExplain,obj.QBDesc
        // );
        console.log(sql);
        if(result==null|| result.affectedRows==0){
            return{
                code:-500,
                message:"参数错误"
            }
        }

        if(result.affectedRows>0){
            return{
                code:0,
                message:"操作成功"
            }
        }

    },
    /**
    * 修改题库是否发布
     * IsPunblish 1为当前已发布 0为未发布
     * @param {*} id 
     * @param {*} IsPublish 
     */
    editPublish:async(id,IsPublish)=>{
        const sql="UPDATE exam_questionbank set QBIsPublish=? WHERE QBID=?";
        const result = await db.query(sql,IsPublish,id);
        if(result.affectedRows==0||result==null){
            return{
                code:-500,
                message:"参数错误"
            }
        }

        if(result.affectedRows>0){
            return{
                code:0,
                message:"操作成功"
            }
        }
    },
    /**
     * 修改题库是否禁用状态
     * 1为本身禁用状态/0为本身启用状态
     * @param {*} id 
     * @param {*} IsBan 
     */
    editIsBan:async(id,IsBan)=>{
         const sql="UPDATE exam_questionbank set QBIsBan=? WHERE QBID=?";
         const result = await db.query(sql,IsBan,id);
         if(result.affectedRows==0||result==null){
            return{
                code:-500,
                message:"参数错误"
            }
        }

        if(result.affectedRows>0){
            return{
                code:0,
                message:"操作成功"
            }
        }
    },

    /**
     * 删除题库
     * @param {*} id 
     * @returns 
     */
    delQuestionBank:async (id)=>{
        const sql="delete  from  exam_questionbank where QBID=?"
        const result = await db.query(sql,id);
        if(result.affectedRows==0||result==null){
            return{
                code:-500,
                message:"参数错误"
            }
        }

        if(result.affectedRows>0){
            return{
                code:0,
                message:"操作成功"
            }
        }

      
    },

    /**
     * 获取当前页的考试题库
     */
    getQuestionBanks: async (page, limit, key) => {
        //每页从page开始拿,拿limit条
        let currPage = (page - 1) * limit
        const sql = `SELECT * from exam_questionbank where QBName like '%${key}%'  ORDER BY QBCreateTime desc limit ${currPage},${limit}`;
        const result = await db.query(sql);

        const sql2 = `SELECT count(*) as count from exam_questionbank where QBName like '%${key}%'`;
        const total = await db.query(sql2);

        if (result == null) {
            return {
                code: -500,
                message: "系统有误,请联系管理员处理"
            }
        }
        return {
            code: 0,
            message: "ok",
            data: {
                data: result,
                total: total[0].count
            }
        }

    },
    
    /**
     * 获取默认题库的题目数量
     */
    getQuestionBankCount:async()=>{
        console.log(234567);
          const sql="SELECT count(*) as count from exam_questions";
          const result=await db.query(sql);
          if(result==null){
            return{
                code:-500,
                message:"系统错误,请联系管理员处理"
            }
          }

          return{
            code:0,
            message:"ok",
            data:{
                count:result[0].count
            }
          }
    }
}

module.exports = examService;